<script setup lang="ts">
import type { User, UserQueryParams } from '#/api';

import { onMounted, reactive, ref } from 'vue';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Select,
  SelectOption,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';
import { RefreshCw } from 'lucide-vue-next';

import { deleteUserApi, getUserListApi, resetPasswordApi } from '#/api';

import AssignRoleModal from './assign-role-modal.vue';
import UserFormModal from './user-form-modal.vue';

// 查询参数
const queryParams = reactive<UserQueryParams>({
  username: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 弹窗
const modalVisible = ref(false);
const assignModalVisible = ref(false);
const currentUser = ref<undefined | User>();

// 使用 vxe-table
const [Grid, gridApi] = useVbenVxeGrid<User>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'username',
        title: '用户名',
        minWidth: 120,
      },
      {
        field: 'nickname',
        title: '昵称',
        minWidth: 120,
      },
      {
        field: 'gender',
        title: '性别',
        width: 80,
        align: 'center',
        slots: { default: 'gender' },
      },
      {
        field: 'email',
        title: '邮箱',
        minWidth: 180,
      },
      {
        field: 'phone',
        title: '手机号',
        width: 130,
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        align: 'center',
        slots: { default: 'status' },
      },
      {
        field: 'roleNames',
        title: '角色',
        minWidth: 200,
        slots: { default: 'roleNames' },
      },
      {
        field: 'createName',
        title: '创建人',
        width: 120,
      },
      {
        field: 'createTime',
        title: '创建时间',
        width: 180,
        slots: { default: 'createTime' },
      },
      {
        field: 'updateName',
        title: '更新人',
        width: 120,
      },
      {
        field: 'updateTime',
        title: '更新时间',
        width: 180,
        slots: { default: 'updateTime' },
      },
      {
        field: 'action',
        title: '操作',
        width: 320,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 查询用户列表
async function fetchUserList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getUserListApi(queryParams);

    // 响应拦截器已经将 MyBatis Plus 格式转换为标准格式
    // 标准格式：{ list, total, pageNum, pageSize }
    if (Array.isArray(data)) {
      // 后端直接返回数组（无分页信息）
      gridApi.setState({
        gridOptions: {
          data,
          loading: false,
          pagerConfig: {
            total: data.length,
            currentPage: queryParams.pageNum || 1,
            pageSize: queryParams.pageSize || 10,
          },
        },
      });
    } else {
      // 标准分页格式（响应拦截器已转换）
      gridApi.setState({
        gridOptions: {
          data: data.list || [],
          loading: false,
          pagerConfig: {
            total: data.total || 0,
            currentPage: data.pageNum || 1,
            pageSize: data.pageSize || 10,
          },
        },
      });
    }
  } catch (error: any) {
    message.error(error?.msg);
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchUserList();
}

// 重置
function handleReset() {
  queryParams.username = undefined;
  queryParams.status = undefined;
  queryParams.pageNum = 1;
  fetchUserList();
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchUserList();
}

// 新增
function handleAdd() {
  currentUser.value = undefined;
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: User) {
  currentUser.value = { ...record };
  modalVisible.value = true;
}

// 分配角色
function handleAssignRole(record: User) {
  currentUser.value = { ...record };
  assignModalVisible.value = true;
}

// 重置密码
function handleResetPassword(record: User) {
  Modal.confirm({
    title: '重置密码',
    content: `确定要重置用户"${record.username}"的密码为默认密码吗？`,
    onOk: async () => {
      try {
        await resetPasswordApi(record.id!, '123456');
        message.success('重置密码成功，新密码为：123456');
      } catch {
        message.error('重置密码失败');
      }
    },
  });
}

// 删除
function handleDelete(record: User) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户"${record.username}"吗？`,
    onOk: async () => {
      try {
        await deleteUserApi(record.id!);
        message.success('删除成功');
        fetchUserList();
      } catch (error: any) {
        // 错误消息由响应拦截器统一处理，这里不需要再显示
        console.error('删除用户失败:', error);
      }
    },
  });
}

// 刷新
function handleRefresh() {
  fetchUserList();
  message.success('刷新成功');
}

// 格式化时间
function formatDateTime(dateTime?: string) {
  if (!dateTime) return '-';
  try {
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch {
    return dateTime;
  }
}

onMounted(() => {
  fetchUserList();
});
</script>

<template>
  <div class="flex h-full flex-col p-4">
    <!-- 搜索表单 -->
    <Card :bordered="false" class="mb-4 flex-shrink-0">
      <Form layout="inline" :model="queryParams">
        <FormItem label="用户名">
          <Input
            v-model:value="queryParams.username"
            placeholder="请输入用户名"
            allow-clear
            @press-enter="handleQuery"
          />
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 150px"
          >
            <SelectOption :value="1">启用</SelectOption>
            <SelectOption :value="0">禁用</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleQuery">查询</Button>
            <Button @click="handleReset">重置</Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 表格 -->
    <Card :bordered="false" class="flex flex-1 flex-col overflow-hidden">
      <div class="mb-4 flex flex-shrink-0 justify-between">
        <Button v-permission="'sys:user:add'" type="primary" @click="handleAdd">
          新增用户
        </Button>
        <Tooltip title="刷新">
          <Button @click="handleRefresh">
            <RefreshCw :size="16" />
          </Button>
        </Tooltip>
      </div>

      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 性别列 -->
          <template #gender="{ row }">
            <span v-if="row.gender === 1">男</span>
            <span v-else-if="row.gender === 2">女</span>
            <span v-else>-</span>
          </template>

          <!-- 状态列 -->
          <template #status="{ row }">
            <Tag v-if="row.status === 1" color="success">启用</Tag>
            <Tag v-else color="error">禁用</Tag>
          </template>

          <!-- 角色列 -->
          <template #roleNames="{ row }">
            <template v-if="row.roleNames && row.roleNames.length > 0">
              <Tag v-for="(role, index) in row.roleNames" :key="index" color="blue">
                {{ role }}
              </Tag>
            </template>
            <span v-else>-</span>
          </template>

          <!-- 创建时间列 -->
          <template #createTime="{ row }">
            <span class="text-xs text-gray-600">{{ formatDateTime(row.createTime) }}</span>
          </template>

          <!-- 更新时间列 -->
          <template #updateTime="{ row }">
            <span class="text-xs text-gray-600">{{ formatDateTime(row.updateTime) }}</span>
          </template>

          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'sys:user:edit'"
                type="link"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </Button>
              <Button
                v-permission="'sys:user:assignRole'"
                type="link"
                size="small"
                @click="handleAssignRole(row)"
              >
                分配角色
              </Button>
              <Button
                v-permission="'sys:user:resetPwd'"
                type="link"
                size="small"
                @click="handleResetPassword(row)"
              >
                重置密码
              </Button>
              <Button
                v-permission="'sys:user:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <UserFormModal
      v-model:visible="modalVisible"
      :user-data="currentUser"
      @success="handleQuery"
    />

    <!-- 分配角色弹窗 -->
    <AssignRoleModal
      v-model:visible="assignModalVisible"
      :user-data="currentUser"
      @success="handleQuery"
    />
  </div>
</template>
